package com.openroom.db;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;

import org.apache.commons.io.FileUtils;
import org.h2.tools.RunScript;

public class DBMigrationRunner {

    public static void main(String[] args) throws IOException {
    }

    public static void createSchema() {
        Collection<File> listFiles = FileUtils.listFiles(new File(
                "migration/sql"), new String[] { "sql" }, false);
        ArrayList<File> list = new ArrayList<File>(listFiles);
        Collections.sort(list, new Comparator<File>() {
            @Override
            public int compare(File o1, File o2) {
                return o1.getName().compareTo(o2.getName());
            }

        });
        for (File file : list) {
            executeScript(file.getAbsolutePath());
        }
    }

    public static int upgradeSchema(int lastRunNum) {
        Collection<File> listFiles = FileUtils.listFiles(new File(
                "migration/sql"), new String[] { "sql" }, false);
        ArrayList<File> list = new ArrayList<File>(listFiles);
        Collections.sort(list, new Comparator<File>() {
            @Override
            public int compare(File o1, File o2) {
                return o1.getName().compareTo(o2.getName());
            }

        });
        int lastNum = lastRunNum;
        for (File file : list) {
            String name = file.getName();
            String string = name.split("_")[0];
            int parseInt = Integer.parseInt(string);
            if (parseInt > lastNum) {
                executeScript(file.getAbsolutePath());
                lastNum = parseInt;
            }
        }
        return lastNum;
    }

    private static void executeScript(final String string) {
        DBHelper instance = DBHelper.getInstance();
        instance.executeWithConnection(new DBTemplate() {
            @Override
            public void execute(Connection connection) throws SQLException {
                try {
                    RunScript.execute(connection, new FileReader(new File(
                            string)));
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
